package com.panshi.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.panshi.IZxArticleApi;
import com.panshi.IZxCommentApi;
import com.panshi.IZxUncheckApi;
import com.panshi.api.AnswerApi;
import com.panshi.api.HomeApi;
import com.panshi.api.SearchApi;
import com.panshi.api.UserApi;
import com.panshi.domain.*;
import com.panshi.domain.vo.PageBean;
import com.panshi.domain.vo.ZxResult;
import com.panshi.po.Article;
import com.panshi.po.Search;
import com.panshi.po.Shox;
import com.panshi.qa.api.HasbeiQaApp;
import com.panshi.qa.api.vo.ItemQueryVo;
import com.panshi.qa.api.vo.QaQuestionFrontdesk;
import com.panshi.qa.api.vo.QuestionResVO;
import com.panshi.utils.LoginVerifyShowPage;
import com.panshi.utils.QiniuUpload;
import com.panshi.utils.TimeBean;
import com.panshi.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.*;

@Slf4j
@Controller
public class ybSystemController {

    @Autowired
    HomeApi homeApi;

    @Autowired
    SearchApi searchApi;

    @Autowired
    HasbeiQaApp hasbeiQaApp;

    @Autowired
    IZxArticleApi iZxArticleApi;

    @Autowired
    IZxUncheckApi iZxUncheckApi;

    @Autowired
    UserApi userApi;

    //初始化首页
    @GetMapping("/homePage")
    public String init(HomeQueryVO homeQueryVO, Model model, HttpSession httpSession){

        Result<Set<Shox>> setResult = homeApi.initHome(homeQueryVO);
        model.addAttribute("rsp",setResult);

        Set<Shox> data = setResult.getData();
        for (Shox is: data)  {
            String dateformat = TimeBean.getTimeFormatText(is.getCreate_time());
            is.setTime(dateformat);
        }

        //首页数据
        model.addAttribute("data",setResult.getData());

        //类型
        model.addAttribute("queryTypeList",iZxArticleApi.queryType().getDate());

        //图文热搜
        model.addAttribute("expertRecommendList",iZxArticleApi.expertRecommend().getDate());

        //最新创作
        model.addAttribute("articleRandomQuerySix",iZxArticleApi.articleRandomQuerySix());

        Map<String, Object> map = hasbeiQaApp.homeQaQuesitonPage().getData();
        Object bigList = map.get("orderList");
        QuestionResVO resVO = JSON.parseObject(bigList.toString(), QuestionResVO.class);

        //登录后展示头部栏目用户信息
        model.addAttribute("userObject",new LoginVerifyShowPage().showPage(userApi,httpSession));

        //相关推荐
        model.addAttribute("answerList",resVO.getOrderList());
        return "homePage";
    }

    //推荐，热门，最新
    @GetMapping("/home/item")
    @ResponseBody
    public ModelAndView findPage(HomeQueryVO homeQueryVO){

        Result<Set<Shox>> setResult = homeApi.initHome(homeQueryVO);
        System.out.println("数据："+setResult);

        Set<Shox> shoxes = setResult.getData();

        ModelAndView modelAndView = new ModelAndView();

        modelAndView.addObject("data",shoxes);

        //将页面拼接
        modelAndView.setViewName("home-list");
        return modelAndView;
    }

    //类型(首页/咨询)
    @RequestMapping("/type")
    public ModelAndView type(int typeId,HttpSession httpSession){
        ModelAndView modelAndView = new ModelAndView();
        //类型
        ZxResult queryTypeList = iZxArticleApi.queryType();
        modelAndView.addObject("queryTypeList",queryTypeList.getDate());

        //类型id
        modelAndView.addObject("typeId",typeId);
        modelAndView.addObject("type",5);

        PageBean pageBean=new PageBean();
        pageBean.setTid(typeId);
        pageBean.setCurrentPage(1);
        pageBean.setPageSize(10);
        pageBean.setType(5);

        Map zxArticleBayType = iZxArticleApi.getZxArticleBayType(pageBean);
        /*咨询类型详情*/
        modelAndView.addObject("totalArticleList",zxArticleBayType.get("data"));
        /*相关推荐*/
        modelAndView.addObject("recommendList",zxArticleBayType.get("correlation"));

        int total = (Integer) zxArticleBayType.get("total");
        int num=(total / 10) + (total % 10 > 0 ? 1: 0);
        modelAndView.addObject("pageNum",num);
        modelAndView.addObject("currentPage",1);

        //看点
        modelAndView.addObject("articleRandomQuerySix",iZxArticleApi.articleRandomQuerySix());

        //登录后展示头部栏
        modelAndView.addObject("userObject",new LoginVerifyShowPage().showPage(userApi,httpSession));

        modelAndView.setViewName("type");
        return modelAndView;
    }

    //收藏
    @RequestMapping("/collectAdd")
    @ResponseBody
    public R collect(Long no,String answerId,Integer type,String articleId,HttpSession httpSession){
        Integer userId =(Integer) httpSession.getAttribute(httpSession.getId());

        R r=null;
        if(type == 20 && answerId!=null){
            QaQuestionFrontdesk qaQuestionFrontdesk=new QaQuestionFrontdesk();
            qaQuestionFrontdesk.setUserId(userId.longValue());
            qaQuestionFrontdesk.setId(Long.valueOf(answerId));

            r = hasbeiQaApp.addCollect(qaQuestionFrontdesk);
            System.out.println("问题收藏："+r);
            return r;
        }else if(type == 10 && answerId!=null){
            ZxArticle zxArticle=new ZxArticle();
            zxArticle.setUserId(userId);
            zxArticle.setId(Integer.valueOf(articleId));

            r = iZxArticleApi.addCollect(zxArticle);
            System.out.println("文章收藏："+r);
            return r;
        }
        return r;
    }

    //发布文章(跳转页)
    @RequestMapping("/articlePublish")
    public String articlePublish(){
        return "publish";
    }

    //发表文章
    @RequestMapping("/article/publish")
    @ResponseBody
    public ZxResult articlePublish(Long t,String title,String content,HttpSession httpSession){

        Integer attribute = (Integer) httpSession.getAttribute(httpSession.getId());

        ZxUncheck zxUncheck=new ZxUncheck();
        zxUncheck.setCreateTime(new Date(t));
        zxUncheck.setTitle(title);
        zxUncheck.setContent(content);
        zxUncheck.setUserId(attribute);

        ZxResult zxResult = iZxUncheckApi.addZxUncheck(zxUncheck);
        return zxResult;
    }

    //提问题（跳转页）
    @RequestMapping("askQuestions")
    public String askQuestions(){
        return "add";
    }

    //发表问题
    @RequestMapping("/ask/questions")
    @ResponseBody
    public R askQuestions(Long t,String title,String content,HttpSession httpSession){

        Integer attribute = (Integer) httpSession.getAttribute(httpSession.getId());

        QaQuestionFrontdesk qqf=new QaQuestionFrontdesk();
        qqf.setContent(content);
        qqf.setUserId(attribute.longValue());
        qqf.setQuestion(title);
        qqf.setTypeId(1);

        R r = hasbeiQaApp.addUncheckQuestoin(qqf);
        return r;
    }

    //图片上传(问答，文章)
    @PostMapping("/upload")
    @ResponseBody
    public String upload(MultipartFile uploadFile, HttpServletRequest request) throws Exception {

        //创建存放图片的临时文件地址
        File file = new File("G:\\IDEA_Workspace\\yb_system\\hasbei\\hasbei-web\\src\\main\\resources\\static\\upload_img");//uploadFile是MultipartFile对象

        uploadFile.transferTo(file);
        UUID uuid = UUID.randomUUID();
        String filename = uuid.toString()+new Date().getTime()+uploadFile.getOriginalFilename();
        //得到图片的url
        String url = QiniuUpload.UploadPic(file.getPath(),filename);
        //生成的文件会存在本地，我这里选择删除它
        file.delete();

        //返回的数据格式必须是就json格式
        return "{\"url\":\""+url+"\"}";
    }

    //搜索
    @GetMapping("/search")
    public ModelAndView search(String kw, Integer page, HttpSession httpSession){
        ModelAndView modelAndView = new ModelAndView();

        SearchQueryVO searchQueryVO = new SearchQueryVO();
        searchQueryVO.setKw(kw);
        searchQueryVO.setCurrent(page);
        Result<SearchPageVO> paging = searchApi.paging(searchQueryVO);
        SearchPageVO searchPageVO = paging.getData();
        searchQueryVO.setPage(searchPageVO.getPage());

        Result<Set<Search>> search = searchApi.search(searchQueryVO);

        Result<Set<Article>> hotSearch = searchApi.hotSearch();

        modelAndView.addObject("sou",hotSearch.getData());

        /*时间去除，通过工具类更改后再放入*/
        Set<Search> data = search.getData();
        for (Search is: data)  {
            String dateformat = TimeBean.getTimeFormatText(is.getPublish_time());
            is.setTime(dateformat);
        }

        /*页数*/
        modelAndView.addObject("fenye",search.getData());
        /*当前页*/
        modelAndView.addObject("mypage",searchPageVO);
        /*搜索关键字*/
        modelAndView.addObject("kw",kw);

        //登录后展示头部栏
        modelAndView.addObject("userObject",new LoginVerifyShowPage().showPage(userApi,httpSession));

        modelAndView.setViewName("search");
        return modelAndView;
    }

    //关于我们
    @RequestMapping("/about")
    public String about(Map<String, Object> map, int aboutId){
        return "about";
    }

    //留言反馈
    @RequestMapping("/messageFeedback")
    public String messageFeedback(){
        return "messageFeedback";
    }
}
